#include "regwidget.h"
#include "ui_regwidget.h"

RegWidget::RegWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RegWidget)
{
    ui->setupUi(this);

    this->cameraThread = CameraThread::getInstance();
    connect(this->cameraThread, &CameraThread::sendImg, this, & RegWidget::receiveImg, Qt::QueuedConnection);
}

RegWidget::~RegWidget()
{
    delete ui;
}

bool RegWidget::addFaceToUser(const QString &accessToken, const QString &userId, const QString &groupId, const QByteArray &imgBase64)
{
    //用于接收api的返回值
    QByteArray replyData;

    QString url = QString(baiduRegUrl).arg(accessToken);
    //构建请求头
    QMap<QString, QString> header;
    header.insert(QString("Content-Type"), QString("application/json"));

    // 构建请求体
    QJsonObject requestObj;
    requestObj.insert("image", QString(imgBase64));
    requestObj.insert("image_type", "BASE64");
    requestObj.insert("group_id", groupId);
    requestObj.insert("user_id", userId);
    requestObj.insert("quality_control", "NORMAL");
    requestObj.insert("liveness_control", "LOW");
    //转换为Json格式
    QByteArray requestData = QJsonDocument(requestObj).toJson();

    bool result = BaiduAi::post_sync(url, header, requestData, replyData);

    if(result)
    {
        QJsonObject responseObj = QJsonDocument::fromJson(replyData).object();
        int errorCode = responseObj.value("error_code").toInt();

        if(errorCode == 0)
        {
            QJsonObject faceObj = responseObj.value("result").toObject();
            QString faceToken = faceObj.value("face_token").toString();
            qDebug() << "Face registration successful, face_token:" << faceToken;
            return true;
        }
        else
        {
            QString errorMsg = responseObj.value("error_msg").toString();
            qDebug() << "Face registration failed, error:" << errorCode << errorMsg;
        }
    }

    return false;
}

void RegWidget::receiveImg(QImage img)
{
    this->img = img;
    update();
}

void RegWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    if(!(this->img.isNull()))
    {
        this->img = this->img.scaled(ui->label_4->width(), ui->label_4->height());
        ui->label_4->setPixmap(QPixmap::fromImage(this->img));
    }
}
//注册按钮槽函数--保存图片且上传到百度AI
void RegWidget::on_pushButton_clicked()
{

    //先确认一下该user_account数据库中不存在
    QString account = ui->lineEdit->text();
    int res = User_Model::getInstance()->doSelectUserData(account);
    if(res == 0)    //已经有这个用户
    {
        QMessageBox::warning(this, "注册界面", "该用户已存在，重新注册");
        return ;
    }

    QDateTime dateTime= QDateTime::currentDateTime();//获取系统当前的时间

    QString str = dateTime.toString("yyyy_MM_dd_hh_mm_ss");//格式化时间
    QString imgPath = "../Photo/" + str + ".jpg";
    this->img.save(imgPath);
    qDebug() << "图片保存:" << imgPath ;

    //将图片转换为Base64格式
    QByteArray imgBase64 = BaiduAi::ImageToBase64(imgPath);

    QString accessToken = BaiduAi::getAccessToken();
    qDebug() << "getaccessToken = " << accessToken;


    //获取界面中当前注册用户的account
    QString user_account = ui->lineEdit->text();
    //组id暂且先不用
    bool result = addFaceToUser(accessToken, user_account, "default_group_id", imgBase64);
    if(result)
    {
        qDebug() << "用户注册成功 with face";
        QMessageBox::information(this, "注册界面", "用户注册成功");
        //这里可以添加注册成功的一些处理，添加到数据库等等
        //该用户不存在，新增用户信息
        User_Model::getInstance()->insertUserData(account);

        //注册成功，返回登陆界面
        emit backToLogin();
    }
    else
    {
        qDebug() << "注册失败";
        QMessageBox::warning(this, "注册界面", "Failed to register user with face");
    }
}

void RegWidget::on_pushButton_2_clicked()
{
    emit backToLogin();
}
